<template>
  <section>
    <div class="grid_12">
      <div v-if="article.operation=='articleEdit'" class="grid_9 omega center-panel">
        <div id="main">
          <div class="up">
            <label>文章标题</label>
            <input v-model="article.title" class="title" />
          </div>
          <div class="up">
            <label>类别</label>
            <input v-model="article.category" class="title" />
          </div>
         <div class="down">
           <mavon-editor ref=maven v-model="article.content" style="min-height: 750px" :value = "content"
                         :subfield="false" :navigation = false :toolbars="editor.toolbar" @save="saveArticle">
           </mavon-editor>
         </div>
        </div>
      </div>
      <div v-if="article.operation=='articleShow'" class="grid_9 omega center-panel">
        <section class="ariticle-panel">
          <label class="article-title">{{article.showTitle}}</label>
          <content v-html="article.showContent" class="article-content markdown-body"></content>
        </section>
      </div>
      <div v-if="article.operation==='backdrop'" class="grid_9 omega center-panel backdrop">
        <h1>使用方法</h1>
        <ol>
          <li>点击根节点添加叶子节点</li>
          <li>叶子节点代表一篇文章,鼠标移动到叶子节点上进行编辑或点击叶子节点进行查看文章</li>
          <li>两个叶子节点可以拖动合并成一个目录，目录之间也可以合并</li>
          <li>两个子节点可以移动到任意一个地方，但是移动到根目录会显示成和根目录并排，刷新即可解决显示问题</li>
          <li>只能删除叶子节点</li>
          <li>tree存在未知bug，导致文章消失，不要太过奇怪</li>
        </ol>
      </div>
      <div class="grid_3 alpha left-panel">
        <el-tree node-key="nodeId" ref="tree"  draggable :data="tree.nodeDatas" :props="tree.defaultProps"
                lazy :load="loadDirNode" @node-click="handleNodeClick" @node-drop="nodeDrop">
          <div class="tree-node-item" slot-scope="{ node, data }">
            <template  v-if="!tree.dragTarget || (tree.dragLeave.id !== node.id)">
              <div class="tree-node-title">{{node.label}}</div>
              <div v-if="node.id === tree.curEditNode.id" class="edit-panel">
                <input v-model="tree.nodeName" :key="node.id" @keyup.enter="addNode(node)" @blur="cancelNode"
                       @click.stop="1+1" />
              </div>
              <div v-if="node.id !== tree.curEditNode.id" class="tree-node-tool">
                <a><i class="fa fa-plus" @click.stop="tree.curEditNode=node"></i></a>
                <a><i v-if="node.isLeaf" class="fa  fa-remove" @click.stop="removeNode(node)"></i></a>
                <a><i v-if="node.isLeaf" class="fa  fa-pencil" @click.stop="editArticle(node)"></i></a>
              </div>
            </template>
            <div v-if="tree.dragTarget && (tree.dragLeave.id === node.id)" class="tree-node-item">
              <input v-model="tree.nodeName" :key="new Date().toDateString()" @keyup.enter="createDir()" @blur="cancelDir"
                     @click.stop="1+1" />
            </div>
          </div>

        </el-tree>
      </div>
    </div>
  </section>
</template>

<script>
// require styles

import { mavonEditor } from 'mavon-editor'
import hljs from 'highlight.js'
import { Tree } from 'element-ui'
import axios from '../../node_modules/axios/dist/axios'
import marked from 'marked/lib/marked'
import '../../node_modules/mavon-editor/dist/css/index.css'
import '../../node_modules/highlight.js/styles/github.css'
marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,
  highlight: function (code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(lang, code, true).value
    } else {
      return hljs.highlightAuto(code).value
    }
  }
})

export default {
  data () {
    return {
      editor: {
        toolbar: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: false, // 中划线
          mark: true, // 标记
          superscript: false, // 上角标
          subscript: false, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: false, // 沉浸式阅读
          htmlcode: false, // 展示html源码
          help: false, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: false, // 下一步
          trash: false, // 清空
          save: false, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: false, // 导航目录
          /* 2.1.8 */
          alignleft: false, // 左对齐
          aligncenter: false, // 居中
          alignright: false, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: false // 预览
        }
      },
      content: '',
      tree: {
        nodeDatas: [],
        defaultProps: {
          children: 'children',
          label: 'label',
          isLeaf: 'isLeaf'
        },
        curEditNode: {},
        nodeName: '',
        dragTarget: {},
        dragLeave: {}
      },
      article: {
        // 编辑文章需要的内容
        title: '',
        content: '',
        category: '',
        editArticleKey: '',
        // articleEdit/backdrop/articleShow
        operation: 'backdrop',
        // 点击节点后显示的内容
        showContent: '',
        showTitle: ''
      }
    }
  },
  components: {
    mavonEditor,
    elTree: Tree
  },
  computed: {
    clearData () {
      return this.article.operation
    }
  },
  watch: {
    clearData () {
      this.article.title = ''
      this.article.content = ''
      this.article.category = ''
      this.editArticleKey = ''
    }
  },
  mounted () {
  },
  methods: {
    saveArticle (value, render) {
      axios.post('/article/saveArticle', {
        title: this.article.title,
        content: value,
        category: this.article.category,
        editArticleKey: this.article.editArticleKey
      }).then(function (res) {
        if (res.data.status === 200) {
          console.log('保存成功')
        }
      })
    },
    queryNode () {

    },
    editArticle (node) {
      let temp = this.$refs.maven
      console.log(temp)
      this.article.operation = 'articleEdit'
      this.article.editArticleKey = node.key
      let _this = this
      axios.get('/article/loadArticle', {params: {articleKey: node.key}}).then(res => {
        if (res.data.status === 200) {
          _this.article.title = res.data.datas.showTitle
          _this.article.content = res.data.datas.showContent
          _this.article.category = res.data.datas.showCategory
        }
      })
    },
    loadDirNode (node, resolve) {
      let _this = this
      axios.get('/article/loadNode', {
        params: {nodeId: node.key}
      }).then(function (res) {
        if (res.data.status === 200) {
          let nodesArray = res.data.datas
          if (_this._.isEmpty(_this.tree.nodeDatas)) { // 加载根节点
            _this.tree.nodeDatas = nodesArray
          } else { //  加载子树节点
            let resultNode = _this.recursionReplace(_this.tree.nodeDatas, node.key)
            if (!_this._.isEmpty(resultNode)) {
              _this.$set(resultNode, 'children', nodesArray)
              resolve(resultNode.children)
            }
          }
        }
      })
    },
    loadArticle (data) {
      let _this = this
      axios.get('/article/loadArticle', {params: {articleKey: data.nodeId}}).then(res => {
        if (res.data.status === 200) {
          _this.article.showTitle = res.data.datas.showTitle
          _this.article.showContent = marked(res.data.datas.showContent)
        }
      })
    },
    handleNodeClick (data, node, self) {
      if (node.isLeaf) {
        this.article.operation = 'articleShow'
        this.loadArticle(data)
      }
    },
    loadArticleTree () {
      let _this = this
      axios.get('/article/loadAticleTree').then(function (res) {
        if (res.data.status === 200) {
          _this.tree.nodeDatas = res.data.datas
        }
      })
    },
    cancelNode () {
      this.tree.curEditNode = {}
      this.tree.nodeName = ''
    },
    recursionReplace (nodes, targetKey) {
      let findResult = {}
      if (this._.isEmpty(nodes)) {
        return findResult
      }

      for (let node of nodes) {
        if (node.nodeId === targetKey) {
          findResult = node
          break
        } else {
          findResult = this.recursionReplace(node.children, targetKey)
          // 回调结果判断是否找到
          if (!this._.isEmpty(findResult)) {
            break
          }
        }
      }
      return findResult
    },
    addNode (node) {
      this.tree.curEditNode = {}
      let _this = this
      // 发送后台处理
      axios.post('/article/addDirNode', {nodeName: this.tree.nodeName, curNodeName: node.label})
        .then(function (res) {
          if (res.data.status === 200) {
            let insertNode = res.data.datas
            let resultNode = _this.recursionReplace(_this.tree.nodeDatas, node.key, insertNode)
            // 找到当前匹配的节点
            if (!_this._.isEmpty(resultNode)) {
              if (!_this._.has(resultNode, 'children')) {
                _this.$set(resultNode, 'children', [])
              }
              // push 是vue提供的7种方法的一种会触发视图更新
              resultNode.children.push(insertNode)
              resultNode.isLeaf = false
              // 页面显示展开
              node.expand()
            }
          }
        })
      this.tree.nodeName = ''
    },
    removeNode (node) {
      let _this = this
      axios.delete('/article/deleteArticle', {data: {nodeId: node.key}}).then(function (res) {
        if (res.data.status === 200) {
          let nodeId = res.data.datas.nodeId
          let parentNodeData = _this.recursionReplace(_this.tree.nodeDatas, node.parent.key)
          // vue对处理数组和对象的更新需要注意，不然不会更新视图
          parentNodeData.children = parentNodeData.children.filter(function (nodeData) {
            if (nodeData.nodeId === nodeId) {
              return false
            }
            return true
          })
          if (_this._.isEmpty(parentNodeData.children)) {
            parentNodeData.isLeaf = true
          }
        }
      })
    },
    createDir () {
      let _this = this
      axios.post('/article/updateDirNode', {
        dirName: _this.tree.nodeName,
        targetNode: _this.tree.dragTarget.key,
        distinationNode: _this.tree.dragLeave.key,
        postion: 'inner'
      }).then(function (res) {
        if (res.data.status === 200) {
          let mergeParentData = _this.recursionReplace(_this.tree.nodeDatas, _this.tree.dragLeave.parent.key)
          mergeParentData.children = res.data.datas
        }
      })
    },
    cancelDir () {
      // enter也会触发blur 清除拖拽节点是产生的临时数据
      this.tree.createDragDir = false
      this.tree.dragTarget = {}
      this.tree.dragLeave = {}
      this.tree.nodeName = ''
    },
    nodeDrop (targetNode, leaveNode, position, event) {
      if (position === 'inner') {
        let isLeaf = leaveNode.data.children.length === 1
        if (isLeaf) {
          this.tree.dragTarget = targetNode
          this.tree.dragLeave = leaveNode
        }
      } else {
        axios.post('/article/updateDirNode', {
          targetNode: targetNode.key,
          distinationNode: leaveNode.key,
          postion: position
        }).then(function (res) {
          // 不需要处理 tree已经处理好了
        })
      }
    }
  }
}
</script>

<style scoped>
@import '../assets/css/article.css';
@import '../assets/css/github-markdown.css';
</style>
